/**
 *@描述：创建知识-上传附件页面，本页面可上传不同类型，不同后缀的文件，包括：图片、文档、表格、语音等多媒体文件。
 *@作者：殷健
 *@创建时间：2022/7/7
 *@最后修改时间：2022/7/7
 */

import {useEffect, useRef, useState} from 'react';
import {Button, Typography, List, Card, Popconfirm, Tag, Modal, Space, Alert, message,Tooltip} from 'antd';
import { PlusOutlined, CloseOutlined, UploadOutlined, SaveOutlined } from '@ant-design/icons';
import CommonIconFont from '@/components/CommonIconFont';
import { AttachmentTypes } from '@/utils/data'
import ProForm, {
    ProFormItem,
    ProFormRadio,
    ProFormText,
    ProFormUploadDragger,
} from '@ant-design/pro-form';

import {
    AttachmentListRequest, DelAttachmentRequest, GetAttachmentPathRequest,
    getAttachmentTypeData,
    uploadKnowledgeAttachmentRequest
} from '../../service';

import { isEmpty } from 'lodash';
import styles from './style.less';
import {ProFormInstance} from "@ant-design/pro-components";
import {useUpdateEffect} from "ahooks";

const { Text } = Typography;

//todo：主组件
const Attachment = (
    {
        title,
        knowledgeId,
        curSection,
        setCurSection,
    }:{
        title:string;
        knowledgeId?:string;
        curSection:AircasKB.Knowledge.SectionItem;
        setCurSection?: (val: AircasKB.Knowledge.SectionItem) => void;
    }

) => {
    //页面初始化函数
    //todo: useEffect函数
    useEffect(()=>{
        if(!knowledgeId){
            message.warn("请首先进入基本信息页面，填写基本信息！");
            setCurSection?.({
                id: 'basic',
                title: '基本信息'
            })
        }
        else{

        }
    },[])

    //todo: useUpdateEffect函数
    useUpdateEffect(() => {
        setCurSection?.(curSection);
    }, [curSection]);
    return (
        <div className={styles.wrapper}>
            <div className={styles.subTitle}>
                <Text>附件管理</Text>
            </div>
            <div className={styles.formControl}>
                <AttachmentList mode="edit" knowledgeId={knowledgeId}/>
            </div>
        </div>
    );
};

//todo: AttachmentList 附件列表组件
const AttachmentList = (
    {
        mode,
        column = 4,
        knowledgeId,
        datalist,
    }: {
        mode: 'view' | 'edit';
        column?: number;
        knowledgeId?:string;
        datalist?:AircasKB.Knowledge.AttachmentListResponse[]
    }) => {
    const [showUploadAttachmentModal, setShowUploadAttachmentModal] = useState<boolean>(false);
    const [ data,setData ]  = useState<AircasKB.Knowledge.AttachmentListResponse[]>([])
    const [ loading,setLoading ] = useState(false);

    //页面初始化函数
    //todo: useEffect函数
    useEffect(()=>{
        if(knowledgeId){
            getAttachmentList()
        }
        else if(datalist && datalist.length>0){
            setData(datalist);
        }
    },[])

    //根据附件ID，删除附件，调用DelAttachmentRequest接口
    //todo: 删除附件
    const delAttachment = async (id?:string) => {
        setLoading(true);
        const res:AircasKB.ResponseType<AircasKB.Knowledge.DelAttachmentResponse> = await DelAttachmentRequest({
            id:id
        });
        if(res.code == 200){
            setLoading(false);
            await getAttachmentList();
            message.success('删除成功！');
        }
        else{
            setLoading(false);
            message.error('删除失败！');
        }
    }

    //根据知识ID获取附件列表函数，仅在编辑是调用，调用AttachmentListRequest接口
    //todo: 根据知识ID获取附件列表
    const getAttachmentList = async ()=>{
        setLoading(true);
        try{
            const res:AircasKB.ResponseType<AircasKB.Knowledge.AttachmentListResponse[]> = await AttachmentListRequest({
                knowledgeId:knowledgeId
            })
            if(res.code == 200){
                setLoading(false);
                if(res.data.length>0){
                    setData(res.data);
                }
            }
            else{
                setLoading(false);
                setData([]);
            }
        }
        catch(e:any) {
            setLoading(false);
            setData([]);
        }


    }

    //附件下载获取路径
    const GetAttachmentPath = async (id:string) => {
        // @ts-ignore
        const res:AircasKB.ResponseType<string> = await GetAttachmentPathRequest({
            attachmentId:id
        })
        if(res.code == 200){
            openDownloadDialog(res.data,'文件.pdf');
            // window.open(res.data);
        }
    }



    function openDownloadDialog(url:any, saveName:any){
        if(typeof url == 'object' && url instanceof Blob)
        {
            url = URL.createObjectURL(url); // 创建blob地址
        }
        var aLink = document.createElement('a');
        aLink.href = url;
        aLink.target = "_blank";
        aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
        var event;
        if(window.MouseEvent) event = new MouseEvent('click');
        else
        {
            event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        }
        aLink.dispatchEvent(event);
    }

    return (
        <div>
            <List
                className={styles.cardList}
                grid={{ gutter: 16, column }}
                itemLayout="vertical"
                loading={loading}
                dataSource={mode === 'edit' ? data.concat([{}]) : data}
                renderItem={(item: AircasKB.Knowledge.AttachmentListResponse) => (
                    <List.Item >
                        {!isEmpty(item.id) && (
                            <Tooltip title={'点击下载'}>
                                <Card className={styles.item} bodyStyle={{ padding: 10 }} onClick={()=>{GetAttachmentPath(item.id || '')}}>
                                    <List.Item.Meta
                                        avatar={
                                            <CommonIconFont
                                                // @ts-ignore
                                                type={`aircaskb-${AttachmentTypes[item.suffix && item.suffix.toLocaleLowerCase()] || 'qita3'}`}
                                                style={{ fontSize: 56 }}
                                            />
                                        }
                                        title={<Tag>{item.type?.value}</Tag>}
                                        description={item.title}
                                    />
                                    {mode === 'edit' && (
                                        <Popconfirm
                                            title="确认删除吗？"
                                            okText="确定"
                                            cancelText="取消"
                                            onConfirm={() => delAttachment(item.id)}
                                        >
                                            <Button
                                                className={styles.removeBtn}
                                                size="small"
                                                type="link"
                                                danger
                                                icon={<CloseOutlined />}
                                            ></Button>
                                        </Popconfirm>
                                    )}
                                </Card>
                            </Tooltip>
                        )}
                        {mode === 'edit' && isEmpty(item.id) && (
                            <div className={styles.addBtn}>
                                <Button
                                    type="link"
                                    size="large"
                                    icon={<PlusOutlined />}
                                    onClick={() => setShowUploadAttachmentModal(true)}
                                >
                                    添加
                                </Button>
                            </div>
                        )}
                    </List.Item>
                )}
            />
            {showUploadAttachmentModal && (
                <UploadAttachmentModal
                    knowledgeId = {knowledgeId}
                    show={showUploadAttachmentModal}
                    onCancel={() => setShowUploadAttachmentModal(false)}
                    onSuccess={getAttachmentList}
                ></UploadAttachmentModal>
            )}

        </div>
    );
};


//todo: UploadAttachmentForm，上传附件组件，modal类型-弹出页面
const UploadAttachmentForm = (
    {
        setShowUploadAttachmentModal,
        knowledgeId,
        onSuccess,
    }:{
        setShowUploadAttachmentModal?: (val:boolean) => void;
        knowledgeId?:string;
        onSuccess?:()=>void;
    }
) => {
    const formRef = useRef<ProFormInstance>();
    const [ loading,setLoading ] = useState(false);
    const [ error ,setError ] = useState(false);

    //保存基本信息
    const handleSubmit = (e:any) =>{
        formRef.current?.validateFieldsReturnFormatValue?.().then((val) => {
            setLoading(true);
            const requestParams:AircasKB.Knowledge.uploadKnowledgeAttachmentRequestParams = {
                file:val.file[0].originFileObj,
                knowledgeId:knowledgeId,
                title:val.title,
                type:val.type,
                cusLabel:"test",
            }
            uploadKnowledgeAttachmentRequest(requestParams).then(res => {
                if(res.code == 200){
                    setLoading(false);
                    setShowUploadAttachmentModal?.(false);
                    onSuccess?.();
                }
                else{
                    setLoading(false);
                    setError(true);
                }
            });
        });
    }
    return (
        <ProForm
            formRef={formRef}
            layout="horizontal"
            className={styles.form}
            labelCol={{
                style: {
                    width: 80,
                },
            }}
            initialValues={{ type: '示范工程' }}
            submitter={false}
        >
            <ProFormRadio.Group
                name="type"
                label="附件类型"
                radioType="button"
                fieldProps={{
                    buttonStyle: 'solid',
                }}
                required
                rules={[
                    {
                        required: true,
                        message: '请选择附件类型',
                    },
                ]}
                request={async () => {
                    const res = await getAttachmentTypeData();
                    formRef.current?.setFieldsValue({
                        type:res.data.length > 0 ? res.data[0].id : "7"
                    });
                    return res.data.map((item) => ({
                        label: item.label,
                        value: item.id,
                    }));
                }}
            />
            <ProFormUploadDragger name="file" label="附件" required max={1}
                                  rules={[
                                      {
                                          required: true,
                                          message: '请上传附件',
                                      },
                                  ]}
            />
            <ProFormText
                name="title"
                label="附件标题"
                required
                rules={[
                    {
                        required: true,
                        message: '请输入附件标题',
                    },
                ]}
            ></ProFormText>
            <ProFormItem>
                <Button
                    size="large"
                    type="primary"
                    htmlType="submit"
                    icon={<SaveOutlined />}
                    style={{ marginLeft: 80 }}
                    loading={loading}
                    onClick={handleSubmit}
                >
                    保存
                </Button>
            </ProFormItem>
            {
                error && <Alert message="上传失败" type="error"  action={
                    <Button size="small" type="text" onClick={handleSubmit}>
                        重试
                    </Button>
                } closable/>
            }
        </ProForm>
    );
};

const UploadAttachmentModal = ({ show, onCancel ,knowledgeId,setKnowledgeId,onSuccess}: {
    show: boolean;
    onCancel?: () => void;
    knowledgeId?:string;

    setKnowledgeId?: (val: string) => void;
    onSuccess?:()=>void;

}) => {
    return (
        <Modal
            title={
                <Space>
                    <UploadOutlined />
                    上传附件
                </Space>
            }
            visible={show}
            width={'95%'}
            centered
            destroyOnClose={true}
            footer={false}
            bodyStyle={{ padding: 20 }}
            onCancel={onCancel}
        >
            <UploadAttachmentForm knowledgeId={knowledgeId} setShowUploadAttachmentModal={onCancel} onSuccess={onSuccess}/>
        </Modal>
    );
};

export default Attachment;
export { AttachmentList };
